#!/usr/bin/evn python
# coding=utf-8

from playhouse.pool import PooledPostgresqlExtDatabase,PostgresqlExtDatabase

from peewee import *

db_config_const = {
    'db_name': 'smart_admin_v2',
    'db_user': 'postgres',
    'db_pass': 'xxxxxxxxxxxxxxxxxx',
    'db_host': 'xxxxxxxxxxxxxxxxx',
    'db_port': 5432,
    'max_connections': 60,
    'stale_timeout': 300,
    'timeout': 20
}

database = PooledPostgresqlExtDatabase(
    db_config_const.get('db_name'),
    max_connections=db_config_const.get('max_connections'),
    stale_timeout=db_config_const.get('stale_timeout'),  # 5 minutes.
    timeout=db_config_const.get('timeout'),
    **{'user': db_config_const.get('db_user'), 'host': db_config_const.get('db_host'),
       'password': db_config_const.get('db_pass'), 'port': db_config_const.get('db_port')})

def GetSession():
    return database

def GetSessionAtomic():
    return database.atomic()

def session_scope_atomic():
    return GetSessionAtomic()
    # if session.is_closed():
    #     # session.connection_context()
    #     session.connect()



from contextlib import contextmanager


@contextmanager
def session_scope():
    session = GetSession()
    if session.is_closed():
        # session.connection_context()
        session.connect()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()


def session_scope2():
    session = GetSession()
    with session.manual_commit():
        session.begin()  # Begin transaction explicitly.
        try:
            yield session
        except:
            session.rollback()  # Rollback -- an error occurred.
            raise
        else:
            try:
                session.commit()  # Attempt to commit changes.
            except:
                session.rollback()  # Error committing, rollback.
                raise


# cursor = GetSession.execute_sql('SELECT * FROM series(?, ?, ?)', (0, 5, 2))
# # for value, in cursor:
# #     print(value)